#!/bin/bash

# 设置环境变量
export GOARCH=amd64
export GOOS=linux

echo "Building for Linux/amd64..."
echo "----------------------------------------------------"

# 删除旧的可执行文件
echo "removing old executable..."
if [ -d "build/linux" ]; then
    rm -rf "build/linux"
fi

# 创建文件夹结构
echo "creating folder structure..."
mkdir -p "build/linux/tinyGW"
mkdir -p "build/linux/tinyGW/public/logs"
mkdir -p "build/linux/tinyGW/public/webroot"
mkdir -p "build/linux/tinyGW/config"
mkdir -p "build/linux/tinyGW/plugin"

# 构建可执行文件
echo "building executable..."
# go build -o "build/linux/tinyGW/zsxagw" -v -ldflags="-w -s"
CGO_ENABLED=0 go build -a -installsuffix cgo -o "build/linux/tinyGW/zsxagw" -ldflags="-w -s -extldflags '-static'"

if [ $? -eq 0 ]; then
    echo "executable built successfully!"
    echo "----------"
    
    # 压缩可执行文件（如果upx可用）
    if command -v upx >/dev/null 2>&1; then
        echo "compressing executable with upx..."
        upx "build/linux/tinyGW/zsxagw"
        echo "executable compressed successfully!"
    else
        echo "upx not found, skipping compression. To install upx:"
        echo "sudo apt update && sudo apt install upx-ucl"
    fi
    
    # 复制public目录
    echo "copying public files..."
    if [ -d "public" ]; then
        cp -r public/* "build/linux/tinyGW/public/"
        # 删除日志文件（如果存在）
        if [ -f "build/linux/tinyGW/public/logs/energy.log" ]; then
            rm "build/linux/tinyGW/public/logs/energy.log"
        fi
    fi
    
    # 复制配置文件
    echo "copying config files..."
    if [ -d "config" ]; then
        cp -r config/* "build/linux/tinyGW/config/"
    fi
    
    # 复制插件目录
    echo "copying plugin files..."
    if [ -d "plugin" ]; then
        cp -r plugin/* "build/linux/tinyGW/plugin/"
    fi
    
    echo "-----------completed!-----------"
    echo "Build output: build/linux/tinyGW/"
    echo "To run: cd build/linux/tinyGW && ./zsxagw"
else
    echo "Build failed!"
    exit 1
fi
